<?php
/**
 * 《退货明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Out.class.php 1048 2010-04-06 04:43:12Z sunxy $
 */
require_once(dirname(__FILE__) . '/MaterialUtil.class.php');

class ReturnedItem extends MaterialUtil {
	public $tbl = Constant::tbl_wl_returned_item;

	public $receive = array(
		'-' => '请选择',
		'1' => '员工',
		'2' => '供应商',
		'9' => '其它',
	);
	
	public $status = array(
		'-' => '请选择',
		'1' => '有效',
		'2' => '无效',
	
		'9' => '其它',
	);
	
	public $orderby = array(
		'-' => '请选择',	
		'mold' => '产品',
		'category' => '大类',
		'subclass' => '小类',
	
		'name' => '名称',
		'standard' => '规格',
		
		'price' => '单价',

		'emp' => '出库人',
		'date' => '出库日期',

		'1' => '创建时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'mold' => '产品',	
		'dept' => '部门',
		'receiver' => '领料人',
		'emp' => '出库人',
		'status' => '状态',
	
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('receive_option', $this->receive);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '退货人',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/returned/item/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == 'mold') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = Name::mold($row['mold']);
		}

		if ($px == 'category') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['category'];
		}

		if ($px == 'subclass') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['subclass'];
		}
		
		if ($px == 'date') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['date'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$material_s = $this->_input($request['material_s']);

		$category_s = $request['category_s'];
		$subclass_s = $request['subclass_s'];

		$name_s = addslashes(trim($request['name_s']));
		$standard_s = addslashes(trim($request['standard_s']));
		
		$t3_s = $this->_input($request['t3_s']);
		$t4_s = $this->_input($request['t4_s']);
		
		$receive_s = $request['receive_s'];
		$receiver_s = $this->_input($request['receiver_s']);
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}

		if (!empty($material_s)) {
			$where .= " AND material = '" . $material_s . "'";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}

		if (!empty($subclass_s) && $subclass_s <> '-') {
			$where .= " AND subclass = '" . $subclass_s . "'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}
		
		if (!empty($standard_s)) {
			$where .= " AND standard LIKE '%" . $standard_s . "%'";
		}

		if (!empty($used_s)) {
			$where .= " AND used = '" . $used_s . "'";
		}
		
		if (!empty($t3_s)) {
			$where .= " AND date >= '" . $t3_s . "'";
		}

		if (!empty($t4_s)) {
			$where .= " AND date <= '" . $t4_s . "'";
		}
		
		if (!empty($receive_s) && $receive_s <> '-') {
			$where .= " AND receive = '" . $receive_s . "'";
		}
		
		if (!empty($receiver_s)) {
			$where .= " AND receiver = '" . $receiver_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		return ' visible = 1';
	
		/*
	
		$emp = $_SESSION['id'];
	
		return sprintf(" (emp = '%s' OR oper = '%s')", $emp, $emp);
		*/
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/returned/item/list');
		return true;
	}

	function xls($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$request['tpl'] = "xls";
		
		$dd = sprintf(" AND %s = '%s'", "DATE_FORMAT(a.createtime, '%Y-%m')", date('Y-m', strtotime($request['t1_s'])));

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/out/list');
		return true;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
				
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
	
			$this->_delete3($id);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2, modifytime = NOW() WHERE id = '%s'";
		}
	
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}

	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}
		
		$emp = $_SESSION['id'];
		
		if ($row['emp'] == $emp || $row['oper'] == $emp) {
			return true;
		}

		return false;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		
		require_once 'In.class.php';
		$in = new In();
		$controller->assign_by_ref('result', $in->_view($id));

		$controller->display($request, 'material/returned/item/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$date = $request['date'];
		$amount = $request['amount'];
		
		$place = $request['place'];
		$content = addslashes($request['content']);
		
		require_once 'In.class.php';
		$in = new In();
		$a = $in->_view($id);
		
		$purchase = $a['receive_x']['purchase'];
		$supplier = $a['receive_x']['supplier'];
		
		require_once(dirname(__FILE__) . '/Amount.class.php');
		$aa = new Amount();
		
		// $aa->_update_returned($a, $amount, $place, $emp);
		
		$name = addslashes($a['name']);
		$standard = addslashes($a['standard']);
		
		require_once(dirname(__FILE__) . '/Returned.class.php');
		$bb = new Returned();
		
		$returned = $bb->_update($purchase, $supplier, $a['receive'], $date, $emp);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, dept, emp, date, purchase, supplier, returned, material, name, standard, unit, price, amount, content, oper, createtime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $date, $purchase, $supplier, $returned, $a['material'], $name, $standard, $a['unit'], $a['price'], $amount, $content, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		
		$this->_update_record_in($purchase, $name, $standard, $amount);

		$controller->display($request, 'info');
		return true;
	}

	function _update_record_in($purchase, $name, $standard, $amount) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		$aa->_returned($purchase, $name, $standard, $amount);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/returned/item/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$emp = $this->_input($request['emp']);
		$date = $request['date'];
		
		$mold = $this->_input($request['mold']);
		
		$receive = $request['receive'];
		$receiver = $this->_input($request['receiver']);
		$receiver_x = addslashes($request['receiver_x']);
		
		$name = addslashes($request['name']);
		$standard = addslashes($request['standard']);

		// 入库单位
		$amount = $request['amount'];
		$unit = $request['unit'];
		$price = $request['price'];		
		
		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET emp = '%s', date = '%s', mold = '%s', name = '%s', standard = '%s', amount = '%s', unit = '%s', price = '%s'";
		$fmt .= ", content = '%s', receive = '%s', receiver = '%s', receiver_x = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $emp, $date, $mold, $name, $standard, $amount, $unit, $price, $content, $receive, $receiver, $receiver_x, $status, $id);
		debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);		

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/returned/item/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row = $this->_view_t($row);
		
		return $row;
	}
	
	function _insert($row, $amount, $date) {
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(mold, material, name, standard, unit, price, amount, content, date, receive, receiver, receiver_x, emp, createtime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now())";
		$sql = sprintf($fmt, $this->tbl, $row['mold'], $row['material'], $row['name'], $row['standard'], $row['unit'], $row['price'], $amount, $content, $date, $row['receive'], $row['receiver'], $row['receiver_x'], $_SESSION['id']);
		debug($sql);
		$db->query($sql);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$num = array(
			'1' => '按次数',
			'2' => '按金额',
		);
		$controller->assign('num_option', $num);

		$controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'material/returned/item/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(price) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'material') {
			$row['a'] = Name::material($row['a']);
		} elseif ($px == 'receiver') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} else {
		
			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	/**
	 * 定时运行
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function tj_daily($controller, $request) {
		$this->pretreat($controller);

		$request['tpl'] = "html4";

		$from = $this->email;
		$to = 'sunxy@tecmold.com';

		$subject = '物料出库情况';

		$this->result_s = 20;
		$this->groupby_s = 'applicant';

		$body = $this->_tj_a($controller, $request);

		$this->mail_html($from, $to, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function z($controller, $request) {
		
		logdate($controller, $request);
		return true;
	}
	
	function x($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE receive = '2' ORDER BY id DESC";
		// $fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$receiver_x = $this->_x($row['receiver'], $row['receiver_x']);
			
			$fmt = "UPDATE %s SET receiver_x = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $receiver_x, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function _x($id, $supplier_x) {
		$j = json_decode($supplier_x);
		
		// var_dump($j);
		
		require_once(dirname(__FILE__) . '/../contact/Supplier.class.php');
		$aa = new Supplier();
		
		$c = $aa->_view($id);
				
		$ret['name'] = $c['name'];
		$ret['fullname'] = $c['fullname'];
		$ret['address'] = $c['address'];
		$ret['web'] = $c['url'];
		
		if (empty($j->contact)) {
			$ret['contact'] = $j->name;
		} else {
			$ret['contact'] = $j->contact;
		}
		
		$ret['mobile'] = $j->mobile;
		$ret['tel'] = $j->tel;
		$ret['fax'] = $j->fax;
		$ret['email'] = $j->email;		
		$ret['content'] = $j->content;
		
		$ret = json_encode($ret);
		
		return addslashes($ret);
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('119');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '出库明细';
		
		$cc = array(
			'新增信息，金额大于100'=>array('w' => "price*amount > 100 AND DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'receiver'),
			'更新信息，金额大于100'=>array('w' => "price*amount > 100 AND DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'receiver'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}
		
		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'material/out/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}

	function tjw($controller, $request) {
		$bb = $this->_list_email('119');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}

		$from = $this->email;
		$subject = '出库明细（周报）';
		
		$cc = array(	
			'新增信息，金额大于500'=>array('w' => "price*amount > 500 AND DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'receiver'),
			'更新信息，金额大于500'=>array('w' => "price*amount > 500 AND DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'receiver'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'material/out/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'receiver';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function view_mold($controller, $request) {
		$id = $request['id'];
	
		$ret = $this->_list_mold($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'material/out/_list_c');
		return true;
	}
	
	function _count($field = 'purchase', $id, $status = 'all') {
	
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `%s` = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id);
		} else {
			$fmt = "SELECT COUNT(*) t FROM %s WHERE `%s` = '%s' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $field, $id, $status);
		}
		debug($sql);
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
	
		return $row['t'];
	}
	
	function _list($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE returned = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE returned = '%s' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
	
			if ($row['type'] == '3') {
				$row['standard'] = sprintf("%s%s", "ф", $row['standard']);
			} else {
				$row['standard'] = $row['standard'];
			}
	
			$ret[] = $row;
		}
	
		return $ret;
	}
}
?>
